package com.cxx.purchasecharge.component.controller.usersecurity;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.usersecurity.AuthorityBean;
import com.cxx.purchasecharge.component.controller.GenericController;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.Authority;
import com.cxx.purchasecharge.dal.AuthorityDao;

@Controller
@RequestMapping ("/authority")
public class AuthorityManager extends GenericController<AuthorityBean>
{
    private static final Logger logger = Logger.getLogger (AuthorityManager.class);

    @Autowired
    private AuthorityDao authorityDao;
    
    public AuthorityManager () 
    {
        super.setViewName("authorityManagement");
    }

    @Override
    public String checkExist(@RequestParam String authorityId, @RequestParam String name, HttpServletRequest request)
    {
        if (StringUtils.isBlank (authorityId))
        {
            // new
            Authority obj = authorityDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long uid = Long.parseLong (authorityId);
            Authority authority = authorityDao.findByName (name);
            if (null != authority && authority.getId () != uid)
            {
                return "false";
            }
        }

        return "true";
    }

    @Override
    public String getAllModel(DataGridRequestForm dataGridRequestForm, HttpServletRequest request)
    {
        /*List <Authority> authoritys = (List <Authority>) authorityDao.findAll ();

        JSONArray jsonArray = JSONArray.fromObject (BeanConvertUtils.authorityList2AuthorityBeanList (authoritys));
        return jsonArray.toString ();*/
        
        List <Authority> authorities = (List <Authority>) authorityDao.findAll ();
        List <AuthorityBean> authorityBeans = new ArrayList <AuthorityBean> ();
        if (null != authorities)
        {
            for (Authority authority : authorities)
            {
                if (null != authority && null == authority.getParent ())
                {
                    AuthorityBean goodsTypeBean = authority2AuthorityBean (authority);
                    authorityBeans.add (goodsTypeBean);
                }
            }
        }
        JSONArray jsonObject = JSONArray.fromObject (authorityBeans);
        return jsonObject.toString ();
    }

    @Override
    public String addModel(AuthorityBean bean, BindingResult bindingResult, HttpServletRequest request)
    {
        //preprocessAuthority (authorityBean, request);
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.save (BeanConvertUtils.authorityBean2Authority (bean));
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String updateModel(AuthorityBean bean, BindingResult bindingResult, HttpServletRequest request)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.save (BeanConvertUtils.authorityBean2Authority (bean));
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String deleteModels(@RequestParam String ids, HttpServletRequest request)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            Authority authority;
            List <Authority> authoritys = new ArrayList <Authority> ();
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String id : idArr)
                {
                    authority = new Authority ();
                    authority.setId (Long.parseLong (id));
                    authoritys.add (authority);
                }
            }
            else
            {
                authority = new Authority ();
                authority.setId (Long.parseLong (ids));
                authoritys.add (authority);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.delete (authoritys);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }
    
    private AuthorityBean authority2AuthorityBean (Authority authority)
    {
        AuthorityBean authorityBean = new AuthorityBean ();
        if (null != authority.getParent ())
        {
            authorityBean.setId (authority.getId () + "");
            authorityBean.setName(authority.getName());
            authorityBean.setEnabled(authority.isEnabled());
            authorityBean.setSystem(authority.isSystem());
            authorityBean.setUrl(authority.getUrl());
            List <AuthorityBean> children = new ArrayList <AuthorityBean> ();
            List <Authority> list = authorityDao.findByParent (authority.getId ());
            if(CollectionUtils.isNotEmpty (list)) 
            {
                for (Authority auth : list)
                {
                    children.add (authority2AuthorityBean (auth));
                }
            }
            authorityBean.setChildren (children);
        }
        else
        {
            authorityBean.setId (authority.getId () + "");
            authorityBean.setName(authority.getName());
            authorityBean.setEnabled(authority.isEnabled());
            authorityBean.setSystem(authority.isSystem());
            authorityBean.setUrl(authority.getUrl());
            List <AuthorityBean> children = new ArrayList <AuthorityBean> ();
            List <Authority> list = authorityDao.findByParent (authority.getId ());
            if(CollectionUtils.isNotEmpty (list)) 
            {
                for (Authority auth : list)
                {
                    children.add (authority2AuthorityBean (auth));
                }
            }
            authorityBean.setChildren (children);
        }
        return authorityBean;
    }

}
